<?php
/**
 * Created by PhpStorm.
 * FileName: AirwayController.class.php
 * User: Administrator
 * Date: 2018/9/11
 * Time: 16:59
 */

namespace Admin\Controller;

use Admin\Controller\AdminController;
use Admin\Model\MoneyModel;
use Admin\Model\MoneyOutModel;
use Admin\Model\UserModel;
use Common\Lib\Util\LogUtil;

/**
 * Class AirwayController
 * @package Admin\Controller
 * @todo 资金管理模块
 * @menu 资金管理
 * @author fanyuliang
 * @menuAuto index
 * @order 502
 * @icon article.png
 */
class MoneyController extends AdminController {

    private $moneyModel;
    private $moneyOutModel;
    private $userModel;

    function __construct() {
        parent::__construct();
        $this->moneyModel = new MoneyModel();
        $this->moneyOutModel = new MoneyOutModel();
        $this->userModel = new UserModel();
    }

    /**
     * @todo 资金流水
     * @menu 资金流水
     * @order 1
     */
    public function index() {
        $this->setForm();
        $where = array();
        if(IS_POST){
            if(I('user_id')){
                $where['user_id'] = I('user_id');
                $searchUserName = $this->userModel->where(array('id' => $where['user_id']))->getField('real_name');
                $this->assign('searchUserName',$searchUserName);
            }
            $order_from_date = I('order_from_date');
            $order_to_date = I('order_to_date');
            if ($order_from_date && $order_to_date) {
                $where['add_time'] = array('between',sprintf('%s,%s',strtotime(sprintf('%s 00:00:00',$order_from_date)),strtotime(sprintf('%s 23:59:59',$order_to_date))));
                $this->assign('order_from_date',strtotime($order_from_date));
                $this->assign('order_to_date',strtotime($order_to_date));
            } else if ($order_from_date) {
                $where['add_time'] = array('egt',strtotime(sprintf('%s 00:00:00',$order_from_date)));
                $this->assign('order_from_date',strtotime($order_from_date));
            } else if ($order_to_date) {
                $where['add_time'] = array('elt',strtotime(sprintf('%s 23:59:59',$order_to_date)));
                $this->assign('order_to_date',strtotime($order_to_date));
            }
        }
        $pageSize = 15;
        $data = $this->moneyModel->getList($where,$pageSize);
        $this->setPageData($data);
        $this->display();
    }

    /**
     * @todo 提现记录
     * @menu 提现记录
     * @order 2
     */
    public function transfer() {
        $this->setForm();
        $where = array();
        if(IS_POST){
            if(I('user_id')){
                $where['user_id'] = I('user_id');
                $searchUserName = $this->userModel->where(array('id' => $where['user_id']))->getField('real_name');
                $this->assign('searchUserName',$searchUserName);
            }
            $order_from_date = I('order_from_date');
            $order_to_date = I('order_to_date');
            if ($order_from_date && $order_to_date) {
                $where['add_time'] = array('between',sprintf('%s,%s',strtotime(sprintf('%s 00:00:00',$order_from_date)),strtotime(sprintf('%s 23:59:59',$order_to_date))));
                $this->assign('order_from_date',strtotime($order_from_date));
                $this->assign('order_to_date',strtotime($order_to_date));
            } else if ($order_from_date) {
                $where['add_time'] = array('egt',strtotime(sprintf('%s 00:00:00',$order_from_date)));
                $this->assign('order_from_date',strtotime($order_from_date));
            } else if ($order_to_date) {
                $where['add_time'] = array('elt',strtotime(sprintf('%s 23:59:59',$order_to_date)));
                $this->assign('order_to_date',strtotime($order_to_date));
            }
            if(I('status') != ''){
                $where['status'] = I('status');
            }
        }
        $pageSize = 15;
        $data = $this->moneyOutModel->getList($where,$pageSize);
        $this->setPageData($data);
        $this->display();
    }

    /**
     * @todo 确认提现
     */
    public function setTransfer() {
        $response = array('status' => false, 'msg' => '提现失败!');
        $id = I('id');
        $row = $this->moneyOutModel->detail(array('id' => $id));
        if ($row['status'] == 1) {
            $response['msg'] = '您已提现过，请勿重复操作!';
            $this->ajaxReturn($response);
        }
        $res = $this->handleWxTransfer($row);
        if ($res && is_array($res)) {
            $returnMsg = $res['return_msg'];
            // 提现成功
            if ($res['return_code'] == 'SUCCESS' && $returnMsg['result_code'] == 'SUCCESS') {
                $paymentNo = $res['payment_no'];
                $rs = $this->moneyOutModel->update(array('status' => 1,'payment_no' => $paymentNo),array('id' => $id));
                if ($rs !== false) {
                    $response['status'] = true;
                    $response['msg'] = '提现成功!';
                    // 扣减相应的账户余额
                    $this->userModel->where(array('id' => $row['user_id']))->setDec('money',$row['money']);
                    $this->handleCapitalFlow($row['user_id'],$row['money'],2,'客户提现');
                }
            }
        }
        LogUtil::info($res);
        $this->ajaxReturn($response);
    }

    // 资金流水处理
    private function handleCapitalFlow ($userId,$money=0,$type=0,$remark='') {
        $moneyData = array(
            'user_id' => $userId,
            'money' => $money,
            'type' => $type,
            'remark' => $remark
        );
        $this->moneyModel->add($moneyData);
    }

    // 微信提现处理
    private function handleWxTransfer($data) {
        require_once dirname(__FILE__).'/../../../ThinkPHP/Library/Vendor/WxpayAPI/lib/WxPay.Business.php';
        $options = array(
            'mchAppId' => 'wx429f7b71d46c2c49',
            'mchId' => '1511581571',
            'mchKey' => '43210987659876543210zhangshengli',
            'openid' => $data['user']['openid'],
            'amount' => $data['money'],
            're_user_name' => $data['user']['real_name'],
            'desc' => sprintf('用户[%s]提现',$data['user']['real_name']),
            'ip' => '140.143.54.34',
            'sslCert' => '/home/web/daigoucert/apiclient_cert.pem',
            'sslKey' => '/home/web/daigoucert/apiclient_key.pem'
        );
        $response = \WxPayBusiness::payToWallet($options);
        return $response;
    }
}